<template>
  <div class="content-section">
    <el-card style="height: 730px">
      <template #header>
        <div class="card-header">
          <span>我的订单</span>
          <el-button type="primary" @click="handleInvoice" size="small"
            >我的发票</el-button
          >
        </div>
      </template>

      <!-- 表格加载状态 -->
      <el-table
        :data="orders"
        style="width: 100%; height: 580px"
        @selection-change="handleSelectionChange"
        border
        v-loading="loading"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="out_no" label="订单号" width="160" />

        <el-table-column label="名称">
          <template #default="{ row }">
            <el-tooltip :content="row.title" placement="top" effect="dark">
              <span class="name-link" @click="handleNameClick(row)">
                {{ row.title }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="addTime" label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.addTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="payTypeTxt" label="支付方式" width="120">
        </el-table-column>

        <el-table-column prop="price" label="支付金额" width="120">
          <template #default="{ row }"> ￥{{ row.price }} </template>
        </el-table-column>

        <el-table-column label="支付状态" width="120">
          <template #default="{ row }">
            <el-tag :type="payStatusMap[row.payStatus]?.type || 'default'">
              {{ payStatusMap[row.payStatus]?.text || "未知" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <!-- 待支付：显示“去支付”按钮 -->
            <el-button
              v-if="row.payStatus === '0'"
              type="text"
              size="small"
              @click="goToPay(row)"
              style="color: #ecaa7a"
            >
              立即支付
            </el-button>

            <!-- 已支付：显示“申请发票”，已开票禁用 -->
            <el-button
              v-else-if="row.payStatus === '1'"
              type="text"
              size="small"
              @click="applyTicket(row)"
              :disabled="row.hasInvoice"
            >
              申请发票
            </el-button>

            <!-- 已过期：不可点击 -->
            <el-button
              v-else-if="row.payStatus === '-1'"
              type="text"
              size="small"
              disabled
            >
              ------------
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-button
          type="primary"
          plain
          @click="applyBatchTicket"
          style="margin-top: 20px"
        >
          批量申请开票
        </el-button>
        <Pagination
          :total="Number(total)"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page="search.pageNum"
          :limit="search.pageSize"
        ></Pagination>
      </div>
    </el-card>

    <!-- 开票弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="发票信息" width="500px">
      <div v-loading="submitLoading">
        <el-form :model="form" label-width="120px" ref="formRef">
          <el-form-item label="总金额">
            <el-text style="color: #eb5757">{{ form.amount }} 元</el-text>
            <span
              v-if="selectedOrders.length > 1"
              style="color: #15161866; margin-left: 8px"
            >
              包含 {{ selectedOrders.length }} 个订单，将开具1张发票
            </span>
          </el-form-item>
          <!-- 抬头类型下拉 -->
          <el-form-item label="抬头类型">
            <el-select
              v-model="form.companyType"
              placeholder="请选择抬头类型"
              clearable
              @change="onTypeChange"
            >
              <el-option label="企业" value="company" />
              <el-option label="个人/非企业" value="person" />
            </el-select>
          </el-form-item>

          <!-- 企业：公司下拉 + 添加 -->
          <el-form-item label="公司名称" v-if="form.companyType === 'company'">
            <el-select
              v-model="form.companyName"
              placeholder="请选择公司"
              filterable
              @change="onCompanyChange"
              style="width: 250px"
            >
              <el-option
                v-for="item in companyOptions"
                :key="item.id"
                :label="item.companyName_forList"
                :value="item.companyName"
              />
            </el-select>
            <!-- <el-button
              type="text"
              icon="el-icon-plus"
              @click="addNewCompany"
              style="margin-left: 8px"
              >添加企业
            </el-button> -->
          </el-form-item>

          <!-- 个人：姓名下拉 + 添加 -->
          <el-form-item label="姓名" v-if="form.companyType === 'person'">
            <el-select
              v-model="form.companyName"
              placeholder="请选择姓名"
              filterable
              @change="onPersonChange"
              style="width: 250px"
            >
              <el-option
                v-for="item in personalOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.realName"
              />
            </el-select>
            <!-- <el-button
              type="text"
              icon="el-icon-plus"
              @click="addNewPerson"
              style="margin-left: 8px"
              >添加姓名
            </el-button> -->
          </el-form-item>

          <!-- 联动显示税号/身份证号 -->
          <el-form-item
            :label="form.companyType === 'company' ? '公司税号' : '身份证号'"
          >
            <el-input
              :disabled="disabledinput"
              v-model="form.companyNo"
              :placeholder="
                form.companyType === 'company'
                  ? '请输入公司税号'
                  : '请输入身份证号'
              "
            />
          </el-form-item>

          <el-form-item label="电子邮箱">
            <el-input
              :disabled="disabledinput"
              v-model="form.email"
              placeholder="请输入接收电子发票的邮箱"
            />
          </el-form-item>

          <div v-if="form.companyType === 'company'" class="auth-tip">
            <template v-if="!companyOptions.length">
              请先到 【用户认证】 添加企业相关信息
            </template>
            <template v-else>
              如需修改企业信息，请到 【用户认证】 提交修改
            </template>
          </div>

          <div v-else class="auth-tip">
            <template
              v-if="
                !personalOptions.length || personalOptions[0].realName === ''
              "
            >
              请先到 【用户认证】 进行个人认证
            </template>
            <template v-else>
              如需修改个人信息，请到 【用户认证】 提交修改
            </template>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm"
            >提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增公司弹窗 -->
    <el-dialog
      v-model="companyDialogVisible"
      title="新增公司"
      width="500px"
      @open="resetCompanyForm"
    >
      <el-form :model="companyForm" label-width="120px">
        <el-form-item label="公司名称">
          <el-input
            v-model="companyForm.companyName"
            placeholder="请输入公司名称"
          />
        </el-form-item>
        <el-form-item label="公司税号">
          <el-input
            v-model="companyForm.companyNo"
            placeholder="请输入公司税号"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="companyForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="营业执照">
          <el-upload
            class="upload-demo"
            :action="''"
            :auto-upload="false"
            accept="image/*,application/pdf"
            :before-upload="beforeLicenseUpload"
            @change="handleCompanyLicenseChange"
            :file-list="companyLicenseList"
            list-type="text"
          >
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="companyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCompany">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 个人认证弹窗 -->
    <el-dialog
      v-model="personDialogVisible"
      title="个人认证"
      width="500px"
      @open="resetPersonForm"
    >
      <el-form :model="personForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="personForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="personForm.cardNo" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="personForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="personDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePerson">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认  支付弹窗 -->
    <el-dialog
      title="支付方式"
      v-model="ConfirmPayVisible"
      width="800px"
      center
    >
      <div class="pay-modal-content">
        <h3 class="pay-title">{{ payInfo.scriptTxt }}</h3>
        <div class="pay-options">
          <div
            class="qr-item"
            :class="{ selected: payMethod === 'wechat' }"
            @click="selectPay('wechat')"
          >
            <div class="qr-label">支付</div>
            <div class="qr-wrapper">
              <img :src="payInfo.wechat_qr" alt="微信二维码" />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ConfirmPayVisible = false">取消</el-button>
          <el-button type="primary" @click="CompletePay"
            >我已完成支付</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 我的发票列表弹窗 -->

    <el-dialog
      title="发票列表"
      v-model="invoiceDialogVisible"
      width="800px"
      center
    >
      <div class="invoice-modal-content">
        <el-table :data="invoiceList" style="width: 100%" border height="300px">
          <el-table-column prop="title" label="抬头" width="250" />
          <el-table-column prop="no" label="税号" width="220" />
          <el-table-column prop="faPiaoType" label="发票类型" width="100">
            <template #default="{ row }">
              {{ row.faPiaoType === "company" ? "企业" : "个人/非企业" }}
            </template>
          </el-table-column>
          <el-table-column prop="money" label="发票金额" width="100">
            <template #default="{ row }"> ￥ {{ row.money }} </template>
          </el-table-column>
          <el-table-column prop="myStatus" label="发票状态">
            <template #default="{ row }">
              {{
                row.myStatus === "0"
                  ? "审核中"
                  : row.myStatus === "1"
                  ? "已开具"
                  : row.myStatus === "-1"
                  ? "审核不通过"
                  : "未知状态"
              }}
            </template>
          </el-table-column>
        </el-table>

        <reportPagination
          :total="Number(invoiceQuery.total)"
          @current-change="handleCurrentChangeinvoice"
          @size-change="handleSizeChangeinvoice"
          :page="invoiceQuery.pageNum"
          :limit="invoiceQuery.pageSize"
        ></reportPagination>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="invoiceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="invoiceDialogVisible = false"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import reportPagination from '../../components/reportPagination.vue'
import { nextTick, onMounted, reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { order } from '../../api/order'
import { reportApi } from '../../api/report.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const handleNameClick = (row) => {
  if (row.price === '0') {
    // 解析免费报告详情页的完整URL
    const freeUrl = router.resolve({
      name: 'productDetail',
      params: { code: row.report_code }
    }).href;

    // 在新标签页打开免费报告
    window.open(freeUrl, '_blank');
  } else {
    // 解析付费报告详情页的完整URL
    const paidUrl = router.resolve({
      name: 'productDetailcharge',
      params: { code: row.report_code }
    }).href;

    // 在新标签页打开付费报告
    window.open(paidUrl, '_blank');
  }
}

// 日期格式
const formatTime = ts => dayjs.unix(typeof ts === 'string' ? Number(ts) : ts).format('YYYY-MM-DD HH:mm')
const formRef = ref(null)
// 支付图标
const paymentMethodIcons = {
  wxPay: 'iconfont icon-weixinzhifu',
  aliPay: 'iconfont icon-zhifubao'
}
const payStatusMap = {
  '0': { text: '待支付', type: 'warning' },
  '1': { text: '已支付', type: 'success' },
  '-1': { text: '已过期', type: 'info' }
}
// 列表与加载状态
const orders = ref([])
const loading = ref(false)
const selectedOrders = ref([])
const tableRef = ref(null)
// 弹窗与提交状态
const dialogFormVisible = ref(false)
const submitLoading = ref(false)
const invoiceDialogVisible = ref(false)

// 下拉数据
const companyOptions = ref([])    // 企业列表：{id, companyName, companyNo, email}
const personalOptions = ref([])   // 个人列表：{id, realName, cardNo, email}

// 表单模型
let form = reactive({
  companyType: 'company',
  companyName: '',
  companyNo: '',
  amount: 0,
  email: ''
})




// 新增公司弹窗
const companyDialogVisible = ref(false)
const companyLicenseList = ref([])
const beforeLicenseUpload = file => {
  const ok = file.type.startsWith('image/') || file.type === 'application/pdf'
  if (!ok) ElMessage.error('仅支持图片或 PDF')
  return ok
}
const handleCompanyLicenseChange = (file, lst) => {
  companyLicenseList.value = lst
  companyForm.companyPic = file.raw
}
const companyForm = reactive({
  companyName: '',
  companyNo: '',
  email: ''
})
const companyId = ref('')
// 个人认证弹窗
const personDialogVisible = ref(false)
const personForm = reactive({
  realName: '',
  cardNo: '',
  email: ''
})

// 添加企业
const addNewCompany = () => {
  companyDialogVisible.value = true
}
// 企业提交
const saveCompany = async () => {
  if (!companyForm.companyName || !companyForm.companyNo || !companyForm.email) {
    return ElMessage.error('请填写完整公司信息')
  }
  try {
    const payload = new FormData()
    payload.append('companyName', companyForm.companyName)
    payload.append('companyNo', companyForm.companyNo)
    payload.append('email', companyForm.email)
    if (companyForm.companyPic) payload.append('companyPic', companyForm.companyPic)


    const res = await order.GetCompanyInfo(payload)
    if (res.code === 0) {
      ElMessage.success('新增公司成功')
      companyDialogVisible.value = false

      // 新增成功后重新拉取公司列表
      const listRes = await order.GetCompanyInfo()
      if (listRes.code === 0 && Array.isArray(listRes.data.certCompany.info)) {
        companyOptions.value = listRes.data.certCompany.info
      }
    } else {
      throw new Error(res.message || '未知错误')
    }
  } catch (err) {
    ElMessage.error('保存失败：' + err.message)
  }
}

// 添加姓名
const addNewPerson = () => {
  personDialogVisible.value = true
}
// 个人提交
const savePerson = async () => {
  if (!personForm.realName || !personForm.cardNo || !personForm.email) {
    return ElMessage.error('请填写完整个人信息')
  }
  try {
    const payload = new FormData()
    payload.append('realName', personForm.realName)
    payload.append('cardNo', personForm.cardNo)
    payload.append('email', personForm.email)
    if (personForm.idPic) payload.append('idPic', personForm.idPic)
    const res = await order.GetUserInfo(payload)
    if (res.code === 0) {
      ElMessage.success('个人认证成功')
      personDialogVisible.value = false
    } else throw new Error(res.message)
  } catch (err) {
    ElMessage.error('认证失败：' + err.message)
  }
}


// 表格多选
const handleSelectionChange = sel => {
  selectedOrders.value = sel
}

// 打开弹窗时拉取抬头数据
const applyTicket = async row => {
  // 清空之前的选择
  tableRef.value.clearSelection()
  // 手动设置选中当前行（需获取表格ref）
  nextTick(() => {
    tableRef.value.toggleRowSelection(row, true)
  })
  // 后续原有逻辑保持不变
  companyId.value = row.id
  await applyTicketCommon(row.price)

}

// 企业联动：选公司后填公司税号和邮箱
const onCompanyChange = name => {
  const c = companyOptions.value.find(x => x.companyName === name)
  if (c) {
    disabledinput.value = true
    form.companyNo = c.companyNo
    form.email = c.email
  }
}

// 个人联动：选姓名后填身份证号和邮箱
const onPersonChange = name => {
  const p = personalOptions.value.find(x => x.realName === name)
  if (p) {
    form.companyNo = p.cardNo
    form.email = p.email
  }
}

// 切换类型清空
const onTypeChange = () => {
  form.companyName = ''
  form.companyNo = ''
  form.email = ''
}
//发票共同逻辑
const applyTicketCommon = async (amount) => {

  form.companyType = 'company'
  form.companyName = ''
  form.companyNo = ''
  form.amount = amount
  form.email = ''

  dialogFormVisible.value = true
  submitLoading.value = true

  // 同时获取企业信息和个人信息
  let { GetCompanyInfo, GetUserInfo } = order
  await Promise.all([GetCompanyInfo(), GetUserInfo()]).then(commonRes => {
    if (commonRes.every((ele) => ele.code === 0)) {
      companyOptions.value = commonRes[0].data.certCompany.info || []
      const p = commonRes[1].data.certPerson
      personalOptions.value = p ? [{
        id: p.id,
        realName: p.realName,
        cardNo: p.cardNo,
        email: p.email
      }] : []
    }
  }).finally(() => {
    submitLoading.value = false
  })
}
// 批量申请
const applyBatchTicket = async () => {
  if (!selectedOrders.value.length) {
    return ElMessage.warning('请选择至少一个订单进行开票')
  }
  let amount = selectedOrders.value.reduce((acc, cur) => Number(acc) + Number(cur.price), 0)
  await applyTicketCommon(amount)

}

// 提交表单
const submitForm = async () => {
  try {
    submitLoading.value = true
    // 构造参数
    const payload = {
      orderIds: selectedOrders.value.map(item => {

        return item.id
      }),
      faPiaoType: form.companyType,
      companyId: companyOptions.value.find(x => x.companyName === form.companyName)?.id
    }

    console.log('最终提交参数:', payload)

    const res = await order.SubmitInvoice(payload)
    if (res.code === 0) {
      ElMessage.success('发票申请成功')
    } else {
      throw new Error(res.msg)
    }

    dialogFormVisible.value = false

    // 刷新订单列表
    await loadOrders()
  } catch (err) {
    ElMessage.error(err.message || '提交失败')
  } finally {
    submitLoading.value = false
  }
}
const disabledinput = ref(true)
const total = ref(0)
const search = reactive({
  pageNum: 1,
  pageSize: 10
})
const handleCurrentChange = (page) => {
  search.pageNum = page
  loadOrders()
}
const handleSizeChange = (limit) => {
  search.pageSize = limit
  search.pageNum = 1
  loadOrders()
}
// 拉订单
const loadOrders = async () => {
  loading.value = true;
  try {
    const res = await order.SearchMyOrders(search);
    total.value = res.data.myOrderList.num
    orders.value = res.data.myOrderList.info.map(item => ({
      ...item,
      out_no: item.out_no || item.order_number,
      id: item.id || item.orderId,
      hasInvoice: item.IS_getFaPiao > 0
    }));
  } catch {
    ElMessage.error('加载失败');
  } finally {
    loading.value = false;
  }
};

const ConfirmPayVisible = ref(false)
const out_no = ref('')
const payInfo = reactive({ wechat_qr: '', alipay_qr: '', scriptTxt: '' })
// 立即支付
const goToPay = async (row) => {
  const res = await order.gobuy({ code: row.order_code })
  ConfirmPayVisible.value = true
  payInfo.wechat_qr = res.data.userOrderPay.payPic

  out_no.value = res.data.userOrderPay.out_no
  payInfo.scriptTxt = res.data.userOrderPay.scriptTxt
}
// 我已完成支付
const CompletePay = () => {
  reportApi.getOrderStatus({ out_no: out_no.value }).then(res => {
    if (res.data.checkOrder
      .payStatus == 0) {
      ElMessage.error('订单未支付成功 请确认')
      ConfirmPayVisible.value = false
    }
    else if (res.data.checkOrder
      .payStatus == 1) {
      ElMessage.success('订单支付成功 ')
      loadOrders()


      ConfirmPayVisible.value = false
    }
  })

}
const invoiceList = ref([])
const invoiceQuery = reactive({
  pgeNum: 1,
  pageSize: 10,
  total: 0
})
const handleCurrentChangeinvoice = (page) => {
  invoiceQuery.pageNum = page
  handleInvoice()
}
const handleSizeChangeinvoice = (limit) => {
  invoiceQuery.pageSize = limit;
  invoiceQuery.pageNum = 1;  // 重置到第一页
  handleInvoice()
}
// 我的发票列表
const handleInvoice = async () => {
  invoiceDialogVisible.value = true
  const res = await order.GetMyInvoice(invoiceQuery)
  if (res.code === 0) {
    invoiceList.value = res.data.faPiaoList.info
    invoiceQuery.total = res.data.faPiaoList.num
  }

}

onMounted(loadOrders)
</script>

<style lang="scss" scoped>
.content-section {
  animation: fadeIn 0.3s ease;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-operate {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.name-cell,
.payment-method-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
  padding: 12px 16px;
}

.icon-weixinzhifu {
  color: #67c23a;
  font-size: 18px;
}

.icon-zhifubao {
  color: #409eff;
  font-size: 18px;
}

.icon-icon_pdf {
  color: #ff7861;
}
.name-link {
  display: inline-block;
  max-width: 300px; /* 根据你想要的宽度调整 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #409eff; /* Element Plus 主色，也可按需调整 */
  cursor: pointer;
  text-decoration: none; /* 去掉下划线 */
}
.name-link:hover {
  text-decoration: underline;
}
.pay-title {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}
.pay-title {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
}
.pay-options {
  display: flex;
  justify-content: space-around;
  gap: 24px;
}
.qr-item {
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: box-shadow 0.3s;
  text-align: center;
}
.qr-item.selected {
  box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.5);
}
.qr-label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}
.qr-wrapper img {
  width: 180px;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}
.dialog-footer {
  padding: 20px 0;
  text-align: center;
}
.auth-tip {
  margin: 16px 0;
  font-size: 14px;
  color: #606266;
  text-align: center;
}
.auth-link {
  color: #409eff;
  text-decoration: underline;
}
</style>
